package org.example.controller;

import org.example.entity.AnalysisEvent;
import org.example.entity.QueryRequest;
import org.example.service.AnalysisService;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

@RestController
@RequestMapping("/api/ai")
@CrossOrigin(origins = "*")
public class AnalysisController {

    private final AnalysisService analysisService;

    public AnalysisController(AnalysisService analysisService) {
        this.analysisService = analysisService;
    }

    /**
     * AI分析接口 - 返回Server-Sent Events流
     */
    @PostMapping(value = "/analyze", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<AnalysisEvent>> analyzeQuery(@RequestBody QueryRequest request) {
        return analysisService.analyzeQuery(request)
                .map(event -> ServerSentEvent.builder(event).build())
                .onErrorResume(throwable -> {
                    AnalysisEvent errorEvent = AnalysisEvent.error("system", throwable.getMessage());
                    return Flux.just(ServerSentEvent.builder(errorEvent).build());
                });
    }
}